<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名称或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li class="search-item" v-for="item of list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li class="search-item" v-show="hasNoDate">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      t: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoDate () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      // console.log(this.cities)
      if (this.t) {
        clearTimeout(this.t)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.t = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
              console.log(result)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>
<style scoped>
  .search{
    background: #00bcd4;
    height: 43px;
    width: 97%;
    padding: 0 1.5%;
    border-top: 1px solid #fff
  }
  .search-input{
    width: 98%;
    padding: 0 1%;
    box-sizing: border-box;
    line-height: 34px;
    height: 34px;
    text-align: center;
    border: 0px;
    border-radius: 8px;
    margin-top: 4px;
    color: #666;
  }
  .search-content{
    position: absolute;
    top: 92px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    background: #eee;
    z-index: 1
  }
  .search-item {
    line-height: 31px;
    padding-left: 10px;
    color: #666;
    background: #fff;
    border-bottom: 1px solid #ccc;
  }
</style>
